/**
  * 选择了ak或使用IP白名单校验：
  */

package com.qk.common.api;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

@Component
public class BdMapWeatherApi {


    private static final ObjectMapper objectMapper = new ObjectMapper();




    public Map<String, Object> getWeather(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
//        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
//        System.out.println("AK: " + buffer.toString());
        // 解析完整响应，提取实时天气（result.now）
        JsonNode rootNode = objectMapper.readTree(buffer.toString());
//        System.out.println(rootNode);
        // 检查API返回状态是否成功（status=0）
        if (rootNode.get("status").asInt() != 0) {
            throw new Exception("百度天气API调用失败：" + rootNode.get("message").asText());
        }
        JsonNode resultNode = rootNode.get("result");
        JsonNode nowNode = resultNode.get("now"); // 实时天气节点
        JsonNode location = resultNode.get("location");
        Map<String, Object> map = new HashMap();
        map.put("location", location);
        map.put("now", nowNode);

        // 返回实时天气的JSON字符串
        return map;
    }
}